package com.ht.aems.fesmodel;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Dong Shufeng
 *         Date: 2007-3-27
 *         Time: 11:13:48
 */
public class PersistenceUnit extends DefaultUnit {

    private FesPersistence persistence;

    private static int maxId;

    private boolean isAddNew = true;

    public static int getMaxId() {
        return maxId;
    }

    public static void setMaxId(int maxId) {
        PersistenceUnit.maxId = maxId;
    }


    public PersistenceUnit(String name) {
        super(name);
    }

    public PersistenceUnit(int id, String name) {
        super(id, name);
    }

    public PersistenceUnit(int id, String name, int parentUnitId) {
        super(id, name, parentUnitId);
    }

    public void addUnit(AbstractUnit unit) {
        super.addUnit(unit);
        if (isAddNew) {
            setUnitId(unit);
            if (persistence != null)
                persistence.saveUnit(unit);
        }
    }

    public boolean modifyUnit(String name, AbstractUnit unit) {
        if (super.modifyUnit(name, unit))
            if (persistence != null)
                return persistence.saveUnit(unit);
        return false;
    }

    public AbstractUnit removeUnit(String name) {
        AbstractUnit unit = super.removeUnit(name);
        if (persistence != null)
            persistence.removeUnit(unit);
        return unit;
    }

    public void setUnitId(AbstractUnit unit) {
        if (unit.getId() < 0) {
            maxId++;
            unit.setId(maxId);
        } else {
            if (maxId < unit.getId())
                maxId = unit.getId();
        }
    }

    public FesPersistence getPersistence() {
        return persistence;
    }

    public void setPersistence(FesPersistence persistence) {
        this.persistence = persistence;
    }

    public boolean isAddNew() {
        return isAddNew;
    }

    public void setAddNew(boolean addNew) {
        isAddNew = addNew;
    }
}
